<script lang="ts" setup>
import type { SchoolApi } from '#/api/edu/base/school';

import { computed, defineEmits, ref, unref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message, Tabs } from 'ant-design-vue';

import { createSchool, getSchool, updateSchool } from '#/api/edu/base/school';
import { $t } from '#/locales';

import BasicInfo from './base-info.vue';
import ContactList from './contact-list.vue';
import EducationForm from './education-form.vue';
import ExternalList from './external-list.vue';
import FeaturesForm from './features-form.vue';
import IntroductionForm from './introduction-form.vue';
import LocationForm from './location-form.vue';
import MembershipForm from './membership-form.vue';
import QualificationForm from './qualification-form.vue';
import StatusForm from './status-form.vue';

const emit = defineEmits(['success']);
const formData = ref<SchoolApi.School>({} as SchoolApi.School);
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['学校信息'])
    : $t('ui.actionTitle.create', ['学校信息']);
});

/** 表单引用 */
const basicInfoRef = ref<InstanceType<typeof BasicInfo>>();
const membershipInfoRef = ref<InstanceType<typeof MembershipForm>>();
const locationInfoRef = ref<InstanceType<typeof LocationForm>>();
const educationInfoRef = ref<InstanceType<typeof EducationForm>>();
const featuresInfoRef = ref<InstanceType<typeof FeaturesForm>>();
const qualificationInfoRef = ref<InstanceType<typeof QualificationForm>>();
const statusInfoRef = ref<InstanceType<typeof StatusForm>>();
const introductionInfoRef = ref<InstanceType<typeof IntroductionForm>>();
const contactInfoRef = ref<InstanceType<typeof ContactList>>();
const externalListRef = ref<InstanceType<typeof ExternalList>>();

const activeKeys = ref('1'); // 默认展开基础

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const formRefs = [
      { ref: basicInfoRef, label: '基本信息', key: '1' },
      { ref: membershipInfoRef, label: '行政隶属关系', key: '2' },
      { ref: locationInfoRef, label: '位置信息', key: '4' },
      { ref: educationInfoRef, label: '办学属性', key: '5' },
      { ref: featuresInfoRef, label: '教学特色', key: '6' },
      { ref: qualificationInfoRef, label: '资质认证', key: '7' },
      { ref: statusInfoRef, label: '状态信息', key: '8' },
      { ref: introductionInfoRef, label: '学校介绍', key: '9' },
    ];

    // 校验所有表单
    for (const { ref, label, key } of formRefs) {
      if (key !== activeKeys.value) continue; // 跳过未展开
      const valid = await ref.value?.validate();
      if (!valid) {
        message.warn(`保存失败，原因：${label}表单校验失败，请检查！`);
        return;
      }
    }

    drawerApi.lock();

    try {
      // 收集表单值
      const values = await Promise.all(
        formRefs.map(({ ref }) => ref.value?.getValues() ?? {}),
      );
      const contactList = await contactInfoRef.value?.getValues();
      // 合并所有值
      const data = Object.assign({}, unref(formData), ...values, {
        contacts: contactList,
      });

      await (formData.value?.id ? updateSchool(data) : createSchool(data));
      // 关闭并提示
      await drawerApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      drawerApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = {} as SchoolApi.School;
      return;
    }
    // 加载数据
    let data =
      drawerApi.getData<SchoolApi.School>() ?? ({} as SchoolApi.School);
    if (data.id) {
      drawerApi.lock();
      try {
        data = await getSchool(data.id);
      } finally {
        drawerApi.unlock();
      }
    }

    formData.value = data;
  },
});

async function tabChange(key: string) {
  if (key === '3') {
    const membershipValues = (await membershipInfoRef.value?.getValues()) ?? {};
    formData.value = { ...formData.value, ...membershipValues };
  }
}
</script>

<template>
  <Drawer :title="getTitle" class="w-[80%]">
    <Tabs
      v-model:active-key="activeKeys"
      tab-position="left"
      @change="tabChange"
    >
      <Tabs.TabPane key="1" tab="基础信息">
        <BasicInfo ref="basicInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="2" tab="行政隶属关系">
        <MembershipForm ref="membershipInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="3" tab="负责人">
        <ContactList
          ref="contactInfoRef"
          :school-contacts="formData.contacts || []"
        />
      </Tabs.TabPane>
      <Tabs.TabPane key="4" tab="位置信息">
        <LocationForm ref="locationInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="5" tab="办学属性">
        <EducationForm ref="educationInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="6" tab="教学特色">
        <FeaturesForm ref="featuresInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="7" tab="资质认证">
        <QualificationForm ref="qualificationInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="8" tab="状态信息">
        <StatusForm ref="statusInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane key="9" tab="学校介绍">
        <IntroductionForm ref="introductionInfoRef" :school="formData" />
      </Tabs.TabPane>
      <Tabs.TabPane
        key="10"
        tab="与外部系统关系"
        v-if="formData.id"
        v-access:code="['system:dept-external:query']"
      >
        <ExternalList ref="externalListRef" :school-id="formData.id" />
      </Tabs.TabPane>
    </Tabs>
  </Drawer>
</template>
